<template>
  <view class="register-page">
    <!-- 固定的页面头部 -->
    <header class="page-header">
      <view class="back-btn" @click="goBack">
        <uni-icons type="left" size="24" color="#333"></uni-icons>
      </view>
      <h1 class="page-title">创建您的账户</h1>
    </header>

    <!-- 可滚动的内容区域 -->
    <scroll-view class="scroll-content" :scroll-y="true">
      <view class="content-wrapper">
        <view class="avatar-uploader" @click="chooseAvatar">
          <image class="avatar-preview" :src="formData.avatarPreview" mode="aspectFill"></image>
        </view>
        <text class="avatar-prompt">点击上传头像</text>

        <form class="form-container" @submit.prevent="handleRegister">
          <view class="input-group">
            <input class="input-field" type="text" v-model="formData.username" placeholder="账号名 (4-16位, 字母/数字/下划线)" />
          </view>
          
          <view class="input-group">
            <input class="input-field" :type="passwordFieldType.new" v-model="formData.password" placeholder="设置密码" />
            <image class="password-toggle" :src="passwordFieldType.new === 'password' ? '/static/icons/eye-slash.svg' : '/static/icons/eye-open.svg'" @click="togglePasswordVisibility('new')"></image>
          </view>
          
          <view class="input-group">
            <input class="input-field" :type="passwordFieldType.confirm" v-model="formData.confirmPassword" placeholder="确认密码" @input="validatePassword" />
            <image class="password-toggle" :src="passwordFieldType.confirm === 'password' ? '/static/icons/eye-slash.svg' : '/static/icons/eye-open.svg'" @click="togglePasswordVisibility('confirm')"></image>
          </view>
          <text class="error-message" v-if="passwordError">{{ passwordError }}</text>

          <view class="input-group">
            <input class="input-field" type="text" v-model="formData.realName" placeholder="您的真实姓名" />
          </view>

          <!-- [新增] 性别选择 -->
          <view class="input-group gender-group">
            <text class="label">性别</text>
            <view class="gender-selector">
              <view class="gender-option" :class="{ active: formData.sex === '男' }" @click="formData.sex = '男'">男</view>
              <view class="gender-option" :class="{ active: formData.sex === '女' }" @click="formData.sex = '女'">女</view>
            </view>
          </view>
          
          <view class="input-group">
            <input class="input-field" type="number" v-model="formData.phone" placeholder="手机号码" />
          </view>
          
          <view class="agreement-group">
            <checkbox-group @change="onAgreementChange">
              <label class="agreement-label">
                <checkbox :value="true" :checked="formData.agreed" style="transform:scale(0.8)" color="#4A90E2" />
                <view class="agreement-text">
                  <text>我已阅读并同意</text>
                  <text class="link" @click.stop="viewAgreement">《用户协议》</text>
                  <text>和</text>
                  <text class="link" @click.stop="viewPrivacy">《隐私政策》</text>
                </view>
              </label>
            </checkbox-group>
          </view>

          <button class="main-btn" :disabled="!isFormValid" @click="handleRegister">立即注册</button>
        </form>
        
        <p class="login-link">
          <text>已有账号? </text>
          <text class="link" @click="goBack">立即登录</text>
        </p>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, reactive, computed } from 'vue';
import { request } from '@/utils/request.js';
import { BASE_URL } from '@/utils/config.js';

const formData = reactive({
  avatarFileTempPath: '',
  avatarPreview: '/static/icons/default-avatar.png',
  username: '',
  password: '',
  confirmPassword: '',
  realName: '',
  phone: '',
  agreed: false,
  // [修改] 默认值为 '男'，与API文档一致
  sex: '男', 
});

const passwordError = ref('');
const passwordFieldType = reactive({ new: 'password', confirm: 'password' });

const isFormValid = computed(() => {
  const isFieldsFilled = formData.username && formData.password && formData.confirmPassword && formData.realName && formData.phone;
  return isFieldsFilled && formData.agreed && !passwordError.value;
});

const goBack = () => uni.navigateBack();
const chooseAvatar = () => {
  uni.chooseImage({
    count: 1, sizeType: ['compressed'], sourceType: ['album', 'camera'],
    success: (res) => {
      formData.avatarPreview = res.tempFilePaths[0];
      formData.avatarFileTempPath = res.tempFilePaths[0]; 
    },
  });
};
const togglePasswordVisibility = (field) => {
  passwordFieldType[field] = passwordFieldType[field] === 'password' ? 'text' : 'password';
};
const validatePassword = () => {
  passwordError.value = (formData.password && formData.confirmPassword && formData.password !== formData.confirmPassword) ? '两次输入的密码不一致' : '';
};
const onAgreementChange = (e) => {
  formData.agreed = e.detail.value.length > 0;
};
const viewAgreement = () => uni.showToast({ title: '查看用户协议', icon: 'none' });
const viewPrivacy = () => uni.showToast({ title: '查看隐私政策', icon: 'none' });

const handleRegister = async () => {
  if (!isFormValid.value) return;
  validatePassword();
  if (passwordError.value) { return uni.showToast({ title: passwordError.value, icon: 'none' }); }

  uni.showLoading({ title: '注册中...' });

  try {
    let uploadedAvatarUrl = '';
    if (formData.avatarFileTempPath) {
      const uploadResult = await new Promise((resolve, reject) => {
        uni.uploadFile({
          url: BASE_URL + '/upload',
          filePath: formData.avatarFileTempPath,
          name: 'file',
          success: (uploadRes) => {
            const resData = JSON.parse(uploadRes.data);
            if (resData.code === 200) { resolve(resData.data.url); } 
            else { reject(new Error(resData.msg || '上传失败')); }
          },
          fail: (err) => reject(err),
        });
      });
      uploadedAvatarUrl = uploadResult;
    }

    const registerParams = {
      accountUsername: formData.username,
      accountPassword: formData.password,
      userName: formData.realName,
      userSex: formData.sex, 
      userPhone: formData.phone,
      userImg: uploadedAvatarUrl,
    };
    
    await request({ url: '/register', method: 'POST', data: registerParams });

    uni.hideLoading();
    uni.showToast({ title: '注册成功！', icon: 'success' });
    setTimeout(goBack, 1500);
  } catch (error) {
    uni.hideLoading();
    console.error('注册失败:', error);
  }
};
</script>

<style lang="scss" scoped>
/* 保持对齐的布局结构 */
.register-page {
  display: flex; flex-direction: column; height: 100vh; background-color: $uni-bg-color-white;
}
.page-header {
  display: flex; align-items: center; position: relative; text-align: center;
  height: 44px; flex-shrink: 0;
}
.back-btn {
  position: absolute; left: 20rpx; top: 50%; transform: translateY(-50%); padding: 20rpx;
}
.page-title {
  flex-grow: 1; font-size: 36rpx; font-weight: 500; text-align: center;
}
.scroll-content {
  flex: 1; overflow-y: hidden;
}
.content-wrapper {
  padding: 0 60rpx 60rpx;
}
.avatar-uploader {
  width: 180rpx; height: 180rpx; border-radius: 50%; margin: 20rpx auto 0;
  .avatar-preview { width: 100%; height: 100%; border-radius: 50%; background-color: #e9ecef; }
}
.avatar-prompt {
  display: block; text-align: center; margin-top: 16rpx; margin-bottom: 50rpx;
  color: $uni-text-color-light; font-size: 28rpx;
}
.input-group {
  display: flex;
  position: relative; margin-bottom: 36rpx;
}
.input-field {
  width: 100%; height: 100rpx; padding: 0 30rpx; border: 1px solid $uni-border-color;
  border-radius: 24rpx; font-size: 30rpx; background-color: $uni-bg-color;
  transition: all 0.2s;
  &:focus { border-color: $uni-primary; background-color: $uni-bg-color-white; }
}
.password-toggle {
  position: absolute; right: 30rpx; top: 50%; transform: translateY(-50%);
  width: 40rpx; height: 40rpx;
}
.error-message {
  color: $uni-color-error; font-size: 26rpx; margin-top: -20rpx; margin-bottom: 20rpx;
  display: block; padding-left: 10rpx;
}

/* [新增] 性别选择器样式 */
.gender-group {
  display: flex;
  align-items: center;
  justify-content: space-between;
  height: 100rpx;
  padding: 0 30rpx;
  border: 1px solid $uni-border-color;
  border-radius: 24rpx;
  background-color: $uni-bg-color;
  .label {
    font-size: 30rpx;
    color: $uni-text-color-placeholder; // 看起来像 placeholder
  }
}
.gender-selector {
  display: flex;
  border: 1px solid $uni-primary;
  border-radius: 30rpx;
  overflow: hidden;
  .gender-option {
    padding: 10rpx 40rpx;
    font-size: 28rpx;
    color: $uni-primary;
    background-color: $uni-bg-color-white;
    transition: all 0.2s;
    &:first-child {
      border-right: 1px solid $uni-primary;
    }
    &.active {
      background-color: $uni-primary;
      color: white;
    }
  }
}

.agreement-group { margin-top: 30rpx; margin-bottom: 50rpx; }
.agreement-label { display: flex; align-items: center; }
.agreement-text {
  font-size: 26rpx; color: $uni-text-color-light; line-height: 1.5;
  .link { color: $uni-primary; }
}
.main-btn {
  width: 100%; height: 100rpx; line-height: 100rpx;
  background: linear-gradient(135deg, $uni-primary, $uni-accent);
  color: white; border-radius: 50rpx; font-size: 32rpx; font-weight: 500;
  &[disabled] { background: #E0E0E0; background-image: none; }
}
.login-link {
  text-align: center; margin-top: 40rpx; font-size: 28rpx; color: $uni-text-color-light;
  .link { color: $uni-primary; font-weight: 500; }
}
</style>